﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MethodWorx.CMS.Services;
using MethodWorx.CMS.Requests;
using Moq;
using MethodWorx.CMS.Membership;
using MethodWorx.Core.Validation;
using MethodWorx.Core.DomainModel;
using MethodWorx.CMS.UI.Tests.Doubles;
using MethodWorx.CMS.UI.Tests.Helper;
using System.ComponentModel.DataAnnotations;

namespace MethodWorx.CMS.UI.Tests.Services
{
    /// <summary>
    /// Summary description for UserServiceCreateUserTests
    /// </summary>
    [TestClass]
    public class UserServiceCreateUserTests
    {
        public UserServiceCreateUserTests()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        private TestContext testContextInstance;

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test 
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        [TestMethod]
        public void EnsureCreateUserRequestCreatesNewUserInstance()
        {
            var repository = new Mock<IUserRepository>();
            var user = new User();

            repository
                .Setup(r => r.CreateEntityInstance())
                .Returns(user)
                .Verifiable();

            var request = new CreateUserRequestDouble(repository.Object);

            repository.Verify();
            Assert.IsTrue(request.User == user);
        }

        [TestMethod]
        public void EnsureCreateUserValidatesRequest()
        {
            var validator = new Mock<IValidationProvider>();
            var service = new UserService(new Mock<IUserRepository>().Object, new Mock<IPreviewSessionRepository>().Object, null);
            var request = new CreateUserRequest(CreateUserRepository());

            validator.Setup(v => v.Validate(request)).Verifiable();

            service.CreateUser(request, validator.Object, null);

            validator.Verify();
        }

        private static IUserRepository CreateUserRepository()
        {
            var mock = new Mock<IUserRepository>();
            mock.Setup(m => m.CreateEntityInstance())
                .Returns(new User());

            return mock.Object;
        }


        [TestMethod]
        public void EnsureNothingIsAddedWhenWhenRequestIsInvalid()
        {
            var repository = CreateUserRepository();
            var request = new CreateUserRequest(repository);
            var validator = new Mock<IValidationProvider>();
            var uowFactory = new StubUnitOfWorkFactory();
            var service = new UserService(repository, new Mock<IPreviewSessionRepository>().Object, null);

            validator.Setup(v => v.Validate(request)).Returns(false).Verifiable();
            service.CreateUser(request, validator.Object, uowFactory);

            //  no units of work that were commited with anything added
            Assert.IsFalse(uowFactory.UnitsOfWork.Where(uow => uow.IsCommited == true && uow.Added.Count() > 0).Any());
            validator.Verify();


        }

        [TestMethod]
        public void EnsureUserIsAddedWhenRequestIsValid()
        {
            var repository = new Mock<IUserRepository>();
            repository
                .Setup(r => r.CreateEntityInstance())
                .Returns(new User());

            var request = new CreateUserRequestDouble(repository.Object);
            var validator = new Mock<IValidationProvider>();
            var service = new UserService(new Mock<IUserRepository>().Object, new Mock<IPreviewSessionRepository>().Object, null);
            var uowFactory = new StubUnitOfWorkFactory();

            validator.Setup(v => v.Validate(request)).Returns(true).Verifiable();

            service.CreateUser(request, validator.Object, uowFactory);

            Assert.IsTrue(uowFactory.UnitsOfWork.Where(uow => uow.IsCommited == true && uow.Added.OfType<User>().Count() == 1).Any());
            validator.Verify();
        }

        [TestMethod]
        public void EnsureCreateUserRequestContainsRequiredValidationForName()
        {
            var repository = new Mock<IUserRepository>();
            repository
                .Setup(r => r.CreateEntityInstance())
                .Returns(new User());

            var request = new CreateUserRequestDouble(repository.Object);

            DataAnnotationsHelper.AssertPropertyHasAttribute<RequiredAttribute>(request, "Username");
        }

        [TestMethod]
        public void EnsureCreateUserRequestContainsRequiredValidationForPassword()
        {
            var repository = new Mock<IUserRepository>();
            repository
                .Setup(r => r.CreateEntityInstance())
                .Returns(new User());

            var request = new CreateUserRequestDouble(repository.Object);

            DataAnnotationsHelper.AssertPropertyHasAttribute<RequiredAttribute>(request, "Password");
        }

        [TestMethod]
        public void EnsureUniqueUsernameIsCheckedAndRaisesError()
        {
            var uowFactory = new StubUnitOfWorkFactory();

            uowFactory.ThrowUniqueKeyViolationExceptionWhenAdding<User>("Username");

            var repository = new Mock<IUserRepository>();
            repository
                .Setup(r => r.CreateEntityInstance())
                .Returns(new User());

            var request = new CreateUserRequestDouble(repository.Object);
            var service = new UserService(repository.Object, new Mock<IPreviewSessionRepository>().Object, null);
            var validation = new Mock<IValidationProvider>();

            validation
                .Setup(r => r.AddError("Username", "Username already exists"))
                .Verifiable();

            validation
                .Setup(r => r.Validate(request))
                .Returns(true)
                .Verifiable();

            //  create the user
            service.CreateUser(request, validation.Object, uowFactory);

            validation.Verify();
        }

        [TestMethod]
        public void EnsureDetailsAreWrittenFromRequest()
        {
            var repository = new Mock<IUserRepository>();
            repository
                .Setup(r => r.CreateEntityInstance())
                .Returns(new User());

            var request = new CreateUserRequestDouble(repository.Object);
            var validator = new Mock<IValidationProvider>();
            var service = new UserService(new Mock<IUserRepository>().Object , new Mock<IPreviewSessionRepository>().Object, null);
            var uowFactory = new StubUnitOfWorkFactory();

            validator.Setup(v => v.Validate(request)).Returns(true).Verifiable();

            request.Username = "Username";
            request.Password = "Password";
            request.Administrator = true;
            service.CreateUser(request, validator.Object, uowFactory);

            //
            //  ensure there is a unit of work
            //  that has been commited with user details of the request
            Assert.IsTrue(uowFactory.UnitsOfWork.Where(uow => uow.IsCommited == true && uow.Added.OfType<User>().Where
                    (
                        u => u.Username == "Username" && u.Password == "Password" && u.Administrator == true
                    ).Any()).Any());
            validator.Verify();
        }
    }
}
